package com.lh.controller;

import com.lh.enums.PayMethod;
import com.lh.pojo.OrderStatus;
import com.lh.pojo.bo.CreateOrderBO;
import com.lh.pojo.vo.MerchantOrdersVO;
import com.lh.pojo.vo.OrderVO;
import com.lh.service.OrderService;
import com.lh.utils.IMOOCJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program: foodie-dev
 * @description:
 * @author: LH
 * @create: 2022-05-20 15:42
 **/
@Api(value = "订单相关接口", tags = {"订单相关api接口"})
@RestController
@RequestMapping("/orders")
public class OrderController extends BaseController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RestTemplate restTemplate;

    private final static Logger LOG = LoggerFactory.getLogger(OrderController.class);


    @ApiOperation(value = "订单创建", notes = "订单创建", httpMethod = "POST",
            response = IMOOCJSONResult.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/create")
    public IMOOCJSONResult create(
            @RequestBody CreateOrderBO createOrderBO,
            HttpServletRequest request,
            HttpServletResponse response
            ){

        if ((!createOrderBO.getPayMethod().equals(PayMethod.ALIPAY.getType()))
                && (!createOrderBO.getPayMethod().equals(PayMethod.WEIXIN.getType()))){
            IMOOCJSONResult.errorMsg("支付方式不支持!");
        }

        //1.创建订单
        OrderVO orderVO = orderService.create(createOrderBO);
        String orderId = orderVO.getOrderId();

        // 2. 创建订单以后，移除购物车中已结算（已提交）的商品
        /**
         * 1001
         * 2002 -> 用户购买
         * 3003 -> 用户购买
         * 4004
         */
        // TODO 整合redis之后，完善购物车中的已结算商品清除，并且同步到前端的cookie
//        CookieUtils.setCookie(request, response, FOODIE_SHOPCART, "", true);

        // 3. 向支付中心发送当前订单，用于保存支付中心的订单数据
        MerchantOrdersVO merchantOrdersVO = orderVO.getMerchantOrdersVO();
        merchantOrdersVO.setReturnUrl(returnUrl);
        merchantOrdersVO.setAmount(1);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId", "imooc");
        headers.add("password", "imooc");

        HttpEntity<MerchantOrdersVO> entity = new HttpEntity<>(merchantOrdersVO, headers);

        ResponseEntity<IMOOCJSONResult> responseEntity = restTemplate.postForEntity(payReturnUrl, entity, IMOOCJSONResult.class);
        IMOOCJSONResult body = responseEntity.getBody();
        if (body.getStatus() != 200){
            LOG.error("发送错误：{}", body.getMsg());
            return IMOOCJSONResult.errorMsg("支付中心订单创建失败，请联系管理员！");
        }

        return IMOOCJSONResult.ok(orderId);

    }

    @PostMapping("/notifyMerchantOrderPaid")
    public Integer notifyMerchantOrderPaid(
            String merchantOrderId){
        orderService.notifyMerchantOrderPaid(merchantOrderId);
        return HttpStatus.OK.value();

    }

    @ApiOperation(value = "轮询查看订单状态", notes = "轮询查看订单状态", httpMethod = "POST",
            response = IMOOCJSONResult.class,
            produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping("/getPaidOrderInfo")
    public IMOOCJSONResult getPaidOrderInfo(
            String orderId
    ){
        OrderStatus paidOrderInfo = orderService.getPaidOrderInfo(orderId);

        return IMOOCJSONResult.ok(paidOrderInfo);
    }

}
